<template>
  <div ref="chartContainer" v-chart-resize class="chartContainer"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'
import 'echarts/theme/macarons'

const props = defineProps({
  chartData: {
    type: Array,
    default: () => []
  }
})

const chartContainer = ref(null)
let chart = null

const setOptions = (data) => {
  if (!data || !Array.isArray(data)) return

  chart?.setOption({
    grid: {
      top: '20%',
      bottom: 30
    },
    dataset: {
      source: data
    },
    title: {
      text: `设备报警统计${data.total || 0}`,
      left: 'center',
      textStyle: {
        fontSize: 32,
        fontWeight: 'normal',
        color: '#fff'
      }
    },
    tooltip: {
      trigger: 'item',
      padding: 14,
      textStyle: {
        fontSize: 22
      }
    },
    xAxis: {
      type: 'category',
      axisLabel: {
        fontSize: 22
      }
    },
    yAxis: {
      type: 'value', // 明确指定类型
      splitLine: {
        show: false
      },
      axisLabel: {
        fontSize: 22
      }
    },
    label: {
      show: true,
      distance: 2,
      position: 'top'
    },
    series: [
      {
        name: '报警数量',
        type: 'bar',
        barWidth: '40%',
        label: {
          fontSize: 22,
          color: '#fff'
        },
        itemStyle: {
          color: '#30948b'
        }
      }
    ]
  })
}

const initChart = () => {
  if (!chartContainer.value) return
  chart = echarts.init(chartContainer.value)
  setOptions(props.chartData)
}

// 监听数据变化
watch(
  () => props.chartData,
  (val) => {
    setOptions(val)
  },
  { deep: true }
)

onMounted(() => {
  initChart()
})

onBeforeUnmount(() => {
  if (chart) {
    chart.dispose()
    chart = null
  }
})
</script>
<style scoped>
.chartContainer {
  width: 100%;
  height: 100%;
}
</style>
